<template>
  <view class="points-container">
    <!-- 积分头部 -->
    <view class="points-header">
      <PointsDisplay 
        ref="pointsDisplay"
        title="我的积分"
        :showLevel="true"
        :autoRefresh="true"
        @showHistory="showHistoryModal"
      />
    </view>

    <!-- 积分获取方式 -->
    <view class="earn-section">
      <text class="section-title">获取积分</text>
      
      <!-- 分类标签 -->
      <view class="category-tabs">
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'daily' }"
          @click="switchTab('daily')"
        >
          <text class="tab-icon">📅</text>
          <text class="tab-text">每日任务</text>
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'game' }"
          @click="switchTab('game')"
        >
          <text class="tab-icon">🎮</text>
          <text class="tab-text">游戏奖励</text>
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'social' }"
          @click="switchTab('social')"
        >
          <text class="tab-icon">👥</text>
          <text class="tab-text">社交互动</text>
        </view>
      </view>
      
      <!-- 滚动容器 -->
      <view class="actions-scroll" :class="{ 'scroll-enabled': needsScroll }">
        <view class="actions-grid">
          <view 
            class="action-card" 
            v-for="action in filteredActions" 
            :key="action.id" 
            @click="handleAction(action)"
          >
            <view class="card-icon">{{ action.icon }}</view>
            <text class="card-title">{{ action.title }}</text>
            <text class="card-reward">+{{ action.reward }}积分</text>
            <view class="card-status" :class="{ completed: action.completed }">
              <text v-if="action.completed" class="status-text">✓</text>
              <text v-else class="status-text">{{ action.statusText }}</text>
            </view>
          </view>
          
          <!-- 空状态 -->
          <view class="empty-actions" v-if="filteredActions.length === 0">
            <text class="empty-icon">📝</text>
            <text class="empty-text">暂无{{ getTabName() }}内容</text>
            <text class="empty-desc">敬请期待更多功能</text>
          </view>
        </view>
      </view>
    </view>


    <!-- 积分商城入口 -->
    <view class="shop-section">
      <button class="shop-btn" @click="goToShop">
        <text class="shop-icon">🛒</text>
        <text class="shop-text">积分商城</text>
        <text class="shop-arrow">→</text>
      </button>
    </view>
    
    <!-- 历史记录弹窗 -->
    <view class="history-modal" v-if="showHistory" @click="hideHistoryModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">积分记录</text>
          <text class="modal-close" @click="hideHistoryModal">✕</text>
        </view>
        
        <scroll-view class="modal-body" scroll-y="true" :style="{ height: '600rpx' }">
          <view class="history-list">
            <view 
              class="history-item" 
              v-for="record in pointsHistory" 
              :key="record.id"
            >
              <view class="history-icon">{{ record.icon }}</view>
              <view class="history-info">
                <text class="history-title">{{ record.title }}</text>
                <text class="history-time">{{ record.time }}</text>
              </view>
              <view class="history-points" :class="record.type">
                <text class="points-text">{{ record.type === 'earn' ? '+' : '-' }}{{ record.points }}</text>
              </view>
            </view>
            
            <!-- 空状态 -->
            <view class="empty-history" v-if="pointsHistory.length === 0">
              <text class="empty-icon">📝</text>
              <text class="empty-text">暂无积分记录</text>
              <text class="empty-desc">开始使用功能来获得积分吧</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    
    <!-- 签到成功弹窗 -->
    <ToastNotification 
      :visible="showCheckInSuccess" 
      title="签到成功"
      :message="`+${checkInPoints} 积分`"
      type="success"
      icon="✨"
      @close="showCheckInSuccess = false"
    />
  </view>
</template>

<script>
import pointsManager from '@/utils/points-manager.js'
import toastHelper from '@/utils/toast-helper.js'
import PointsDisplay from './components/PointsDisplay.vue'
import PointsActions from './components/PointsActions.vue'
import ToastNotification from '@/components/ToastNotification.vue'

export default {
  components: {
    PointsDisplay,
    PointsActions,
    ToastNotification
  },
  
  data() {
    return {
      activeTab: 'daily',
      showHistory: false,
      pointsHistory: [],
      showCheckInSuccess: false,
      checkInPoints: 0,
      earnActions: [
        {
          id: 1,
          type: 'checkin',
          category: 'daily',
          icon: '📅',
          title: '每日签到',
          description: '每天首次签到获得积分',
          reward: 10,
          completed: false,
          statusText: '未完成',
          completedText: '今日已签到'
        },
        {
          id: 2,
          type: 'task',
          category: 'daily',
          icon: '📋',
          title: '每日任务',
          description: '完成每日任务获得积分',
          reward: 30,
          completed: false,
          statusText: '查看任务'
        },
        {
          id: 3,
          type: 'ad',
          category: 'daily',
          icon: '📺',
          title: '观看广告',
          description: '观看广告视频获得积分',
          reward: 5,
          completed: false,
          statusText: '观看'
        },
        {
          id: 4,
          type: 'gameTime',
          category: 'game',
          icon: '🎮',
          title: '游戏时长奖励',
          description: '每游戏1小时获得积分',
          reward: 20,
          completed: false,
          statusText: '可领取'
        },
        {
          id: 5,
          type: 'achievement',
          category: 'game',
          icon: '🏆',
          title: '成就奖励',
          description: '完成成就获得大量积分',
          reward: 50,
          completed: false,
          statusText: '可领取'
        },
        {
          id: 6,
          type: 'share',
          category: 'social',
          icon: '👥',
          title: '邀请好友',
          description: '邀请好友注册获得积分',
          reward: 100,
          completed: false,
          statusText: '去邀请'
        },
        {
          id: 7,
          type: 'comment',
          category: 'social',
          icon: '💬',
          title: '发表评论',
          description: '在社区发表评论获得积分',
          reward: 15,
          completed: false,
          statusText: '去评论'
        },
        {
          id: 8,
          type: 'like',
          category: 'social',
          icon: '👍',
          title: '点赞互动',
          description: '点赞其他用户内容获得积分',
          reward: 5,
          completed: false,
          statusText: '去点赞'
        },
        {
          id: 9,
          type: 'follow',
          category: 'social',
          icon: '➕',
          title: '关注用户',
          description: '关注新用户获得积分',
          reward: 10,
          completed: false,
          statusText: '去关注'
        },
        {
          id: 10,
          type: 'levelUp',
          category: 'game',
          icon: '⬆️',
          title: '等级提升',
          description: '游戏等级提升获得积分',
          reward: 80,
          completed: false,
          statusText: '可领取'
        },
        {
          id: 11,
          type: 'boss',
          category: 'game',
          icon: '👹',
          title: '击败Boss',
          description: '击败游戏Boss获得积分',
          reward: 120,
          completed: false,
          statusText: '挑战中'
        },
        {
          id: 12,
          type: 'collection',
          category: 'game',
          icon: '💎',
          title: '收集物品',
          description: '收集稀有物品获得积分',
          reward: 60,
          completed: false,
          statusText: '进行中'
        },
        {
          id: 13,
          type: 'weekly',
          category: 'daily',
          icon: '📊',
          title: '周度任务',
          description: '完成周度任务获得积分',
          reward: 200,
          completed: false,
          statusText: '进行中'
        },
        {
          id: 14,
          type: 'streak',
          category: 'daily',
          icon: '🔥',
          title: '连续签到',
          description: '连续签到7天获得积分',
          reward: 100,
          completed: false,
          statusText: '第3天'
        }
      ]
    }
  },
  
  computed: {
    filteredActions() {
      return this.earnActions.filter(action => action.category === this.activeTab)
    },
    
    // 判断是否需要滚动
    needsScroll() {
      // 如果当前分类的功能数量超过4个，则需要滚动
      return this.filteredActions.length > 4
    }
  },
  
  onLoad() {
    this.checkLoginStatus()
    this.loadUserData()
  },
  
  onShow() {
    this.checkLoginStatus()
    this.loadUserData()
  },
  
  methods: {
    // 获取当前标签名称
    getTabName() {
      const tabNames = {
        daily: '每日任务',
        game: '游戏奖励',
        social: '社交互动'
      }
      return tabNames[this.activeTab] || '功能'
    },
    
    // 加载用户数据
    loadUserData() {
      this.updateCheckInStatus()
      this.loadPointsHistory()
    },
    
    // 加载积分历史
    loadPointsHistory() {
      this.pointsHistory = pointsManager.getRecentActivities()
    },
    
    // 显示历史记录弹窗
    showHistoryModal() {
      this.loadPointsHistory()
      this.showHistory = true
    },
    
    // 隐藏历史记录弹窗
    hideHistoryModal() {
      this.showHistory = false
    },
    
    // 检查登录状态
    checkLoginStatus() {
      try {
        const token = uni.getStorageSync('user_token')
        if (!token) {
          // 未登录时，重置所有签到状态
          const checkInAction = this.earnActions.find(action => action.type === 'checkin')
          if (checkInAction) {
            checkInAction.completed = false
            checkInAction.statusText = '未完成'
          }
        }
      } catch (error) {
        console.error('检查登录状态失败:', error)
      }
    },
    
    // 更新签到状态
    updateCheckInStatus() {
      // 检查是否已登录
      const token = uni.getStorageSync('user_token')
      if (!token) {
        return
      }
      
      const checkInAction = this.earnActions.find(action => action.type === 'checkin')
      if (checkInAction) {
        // 使用 pointsManager 获取签到状态（会自动验证用户ID）
        checkInAction.completed = pointsManager.getCheckInStatus()
        checkInAction.statusText = checkInAction.completed ? '已完成' : '未完成'
      }
    },
    
    // 积分变化回调
    onPointsChanged() {
      // 刷新积分显示组件
      if (this.$refs.pointsDisplay) {
        this.$refs.pointsDisplay.refresh()
      }
      
      // 更新历史记录
      this.loadPointsHistory()
      
      // 更新签到状态
      this.updateCheckInStatus()
    },
    
    // 切换标签
    switchTab(tab) {
      this.activeTab = tab
    },
    
    // 处理动作
    handleAction(action) {
      if (action.completed) {
        toastHelper.showToast({
          title: action.completedText || '已完成',
          icon: 'none'
        })
        return
      }
      
      switch (action.type) {
        case 'checkin':
          this.handleCheckIn(action)
          break
        case 'gameTime':
          this.handleGameTimeReward(action)
          break
        case 'achievement':
          this.handleAchievementReward(action)
          break
        case 'share':
          this.handleShare(action)
          break
        case 'ad':
          this.handleWatchAd(action)
          break
        case 'task':
          this.handleTask(action)
          break
        default:
          toastHelper.showError('功能开发中')
      }
    },
    
    // 处理签到
    handleCheckIn(action) {
      // 检查登录状态
      const token = uni.getStorageSync('user_token')
      if (!token) {
        toastHelper.showError('请先登录后再签到')
        return
      }
      
      const hasCheckedIn = pointsManager.getCheckInStatus()
      if (hasCheckedIn) {
        toastHelper.showError('今日已签到')
        return
      }
      
      pointsManager.setCheckInStatus(true)
      pointsManager.addPoints(action.reward, action.title)
      
      // 显示签到成功弹窗
      this.showCheckInSuccess = true
      this.checkInPoints = action.reward
      
      this.onPointsChanged()
    },
    
    // 处理游戏时长奖励
    handleGameTimeReward(action) {
      const gameHours = 2.5
      const rewardPoints = Math.floor(gameHours) * action.reward
      
      if (rewardPoints > 0) {
        pointsManager.addPoints(rewardPoints, action.title)
        uni.showToast({
          title: `获得${rewardPoints}积分`,
          icon: 'success'
        })
        this.onPointsChanged()
      } else {
        uni.showToast({
          title: '游戏时长不足',
          icon: 'none'
        })
      }
    },
    
    // 处理成就奖励
    handleAchievementReward(action) {
      const hasNewAchievement = true
      
      if (hasNewAchievement) {
        pointsManager.addPoints(action.reward, action.title)
        uni.showToast({
          title: `获得${action.reward}积分`,
          icon: 'success'
        })
        this.onPointsChanged()
      } else {
        uni.showToast({
          title: '暂无新成就',
          icon: 'none'
        })
      }
    },
    
    // 处理分享
    handleShare(action) {
      uni.showActionSheet({
        itemList: ['分享到微信', '分享到QQ', '复制邀请链接'],
        success: (res) => {
          if (res.tapIndex === 0) {
            this.performShare('wechat', action)
          } else if (res.tapIndex === 1) {
            this.performShare('qq', action)
          } else if (res.tapIndex === 2) {
            this.copyInviteLink()
          }
        }
      })
    },
    
    // 执行分享
    performShare(platform, action) {
      setTimeout(() => {
        pointsManager.addPoints(action.reward, action.title)
        uni.showToast({
          title: '分享成功',
          icon: 'success'
        })
        this.onPointsChanged()
      }, 1000)
    },
    
    // 复制邀请链接
    copyInviteLink() {
      const inviteLink = 'https://moe-web.com/invite?code=USER123'
      uni.setClipboardData({
        data: inviteLink,
        success: () => {
          uni.showToast({
            title: '邀请链接已复制',
            icon: 'success'
          })
        }
      })
    },
    
    // 处理观看广告
    handleWatchAd(action) {
      uni.showModal({
        title: '观看广告',
        content: '观看30秒广告视频，获得积分奖励',
        success: (res) => {
          if (res.confirm) {
            setTimeout(() => {
              pointsManager.addPoints(action.reward, action.title)
              uni.showToast({
                title: '观看完成',
                icon: 'success'
              })
              this.onPointsChanged()
            }, 2000)
          }
        }
      })
    },
    
    // 处理任务
    handleTask(action) {
      uni.navigateTo({
        url: '/pages/points/tasks/tasks',
        fail: () => {
          uni.showToast({
            title: '任务页面开发中',
            icon: 'none'
          })
        }
      })
    },
    
    // 跳转到商城
    goToShop() {
      uni.switchTab({
        url: '/pages/shop/shop'
      })
    }
  }
}
</script>

<style scoped>
/* 全局页面样式 */
page {
  height: auto;
  overflow-x: hidden;
}

.points-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding-bottom: 40rpx; /* 减少底部内边距 */
  /* 确保容器高度自适应内容 */
  height: auto;
  overflow-x: hidden;
}

/* 积分头部 */
.points-header {
  margin: 20rpx;
}

/* 获取积分区域 */
.earn-section {
  margin: 20rpx;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.1);
  /* 让容器根据内容自动调整高度 */
  height: auto;
  min-height: fit-content;
  /* 确保不会产生额外的滚动空间 */
  overflow: visible;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  display: block;
}

/* 分类标签 */
.category-tabs {
  display: flex;
  gap: 12rpx;
  margin-bottom: 30rpx;
  background: #f0f2f5;
  border-radius: 20rpx;
  padding: 8rpx;
  position: relative;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16rpx 12rpx;
  background: transparent;
  border-radius: 16rpx;
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
  z-index: 2;
}

.tab-item.active {
  background: white;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
  transform: translateY(-2rpx);
}

.tab-item.active::before {
  content: '';
  position: absolute;
  top: -2rpx;
  left: -2rpx;
  right: -2rpx;
  bottom: -2rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 18rpx;
  z-index: -1;
}

.tab-icon {
  font-size: 28rpx;
  margin-bottom: 6rpx;
  transition: all 0.3s ease;
}

.tab-item.active .tab-icon {
  transform: scale(1.1);
}

.tab-text {
  font-size: 22rpx;
  font-weight: bold;
  color: #666;
  transition: all 0.3s ease;
}

.tab-item.active .tab-text {
  color: #667eea;
  font-weight: 600;
}

/* 滚动容器 */
.actions-scroll {
  background: #f8f9fa;
  border-radius: 16rpx;
  padding: 20rpx;
  /* 默认状态：自动高度，不滚动 */
  height: auto;
  overflow: visible;
}

/* 当需要滚动时启用滚动功能 */
.actions-scroll.scroll-enabled {
  max-height: 14.75rem;
  overflow-y: auto;
}

/* 自定义滚动条样式 */
.actions-scroll.scroll-enabled::-webkit-scrollbar {
  width: 6rpx;
}

.actions-scroll.scroll-enabled::-webkit-scrollbar-track {
  background: transparent;
}

.actions-scroll.scroll-enabled::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 3rpx;
}

.actions-scroll.scroll-enabled::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.3);
}

/* 网格布局 */
.actions-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  /* 移除固定最小高度，让内容自适应 */
}

.action-card {
  background: #f8f9fa;
  border-radius: 16rpx;
  padding: 24rpx;
  text-align: center;
  transition: all 0.3s ease;
  position: relative;
  cursor: pointer;
}

.action-card:active {
  transform: scale(0.95);
}

.card-icon {
  font-size: 48rpx;
  margin-bottom: 12rpx;
}

.card-title {
  font-size: 26rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.card-reward {
  font-size: 22rpx;
  color: #4caf50;
  font-weight: bold;
  display: block;
  margin-bottom: 12rpx;
}

.card-status {
  position: absolute;
  top: 12rpx;
  right: 12rpx;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  font-size: 20rpx;
  font-weight: bold;
}

.card-status.completed {
  background: #4caf50;
  color: white;
}

.card-status:not(.completed) {
  background: #667eea;
  color: white;
}

.status-text {
  font-size: 20rpx;
}

/* 空状态 */
.empty-actions {
  grid-column: 1 / -1;
  text-align: center;
  padding: 80rpx 20rpx;
  color: #999;
}

.empty-icon {
  font-size: 80rpx;
  display: block;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 10rpx;
  color: #666;
}

.empty-desc {
  font-size: 24rpx;
  opacity: 0.8;
}

/* 历史记录弹窗 */
.history-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  width: 90%;
  max-width: 600rpx;
  background: white;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 20rpx 40rpx rgba(0, 0, 0, 0.3);
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
}

.modal-close {
  font-size: 36rpx;
  cursor: pointer;
  padding: 10rpx;
}

.modal-body {
  background: #f8f9fa;
}

.history-list {
  padding: 20rpx;
}

.history-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: white;
  border-radius: 12rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.history-icon {
  font-size: 32rpx;
  margin-right: 20rpx;
}

.history-info {
  flex: 1;
}

.history-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.history-time {
  font-size: 22rpx;
  color: #999;
}

.history-points {
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  font-weight: bold;
}

.history-points.earn {
  background: #e8f5e8;
  color: #4caf50;
}

.history-points.spend {
  background: #ffeaea;
  color: #f44336;
}

.points-text {
  font-size: 24rpx;
}

/* 空状态 */
.empty-history {
  text-align: center;
  padding: 80rpx 20rpx;
  color: #999;
}

.empty-icon {
  font-size: 80rpx;
  display: block;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 10rpx;
  color: #666;
}

.empty-desc {
  font-size: 24rpx;
  opacity: 0.8;
}

/* 商城入口 */
.shop-section {
  margin: 20rpx;
  margin-bottom: 20rpx; /* 减少底部间距，避免额外滚动空间 */
}

.shop-btn {
  background: linear-gradient(45deg, #ff6b6b, #ffa500);
  color: white;
  border: none;
  border-radius: 25rpx;
  padding: 30rpx 40rpx; /* 增加垂直内边距 */
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 25rpx rgba(255, 107, 107, 0.3);
  min-height: 90rpx; /* 设置最小高度 */
}

.shop-icon {
  font-size: 32rpx;
  margin-right: 15rpx;
}

.shop-text {
  font-size: 28rpx;
  font-weight: bold;
  margin-right: 15rpx;
}

.shop-arrow {
  font-size: 24rpx;
}
</style>